package com.ruoyi.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.api.annotation.Login;
import com.ruoyi.business.app.vo.AppDictDataVo;
import com.ruoyi.business.app.vo.DownloadVo;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxAppVersion;
import com.ruoyi.business.service.IHcxAppUserService;
import com.ruoyi.business.service.IHcxAppVersionService;
import com.ruoyi.business.vo.HcxAppUserVo;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.AssertUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDictDataService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "通用接口")
@AllArgsConstructor
@RestController
@RequestMapping("/api/common")
public class AppCommonController extends BaseController {


    private final ISysDictDataService dictDataService;

    private final IHcxAppVersionService hcxAppVersionService;

    private final IHcxAppUserService hcxAppUserService;

    @Login
    @ApiOperation("查询字典数据")
    @GetMapping(value = "/dict/list")
    public AjaxResult<List<AppDictDataVo>> dictList(@ApiParam("字典类型") @RequestParam String dictType) {
        List<AppDictDataVo> appDictDataVos = dictDataService.listVo(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, dictType), AppDictDataVo.class);
        return AjaxResult.success(appDictDataVos);
    }



    @ApiOperation("返回最新的版本号")
    @GetMapping("/version/list")
    public AjaxResult<DownloadVo> versionList() {
        List<DownloadVo> downloadVos = hcxAppVersionService.listVo(new LambdaQueryWrapper<HcxAppVersion>().orderByDesc(HcxAppVersion::getAppVersion), DownloadVo.class);
        AssertUtils.isTrue(CollectionUtil.isNotEmpty(downloadVos), "请现在后台维护版本管理");
        return AjaxResult.success(downloadVos.get(0));
    }


    @Login
    @ApiOperation("查询用户有没有父级")
    @GetMapping("/findParent")
    public AjaxResult<Map<String, Object>> findParent() {

        // 查询当前登录用户
        HcxAppUserVo currentUser = hcxAppUserService.queryById(SecurityUtils.getUserId());

        String fullParent = currentUser.getInviteFullCode();


        Map<String, Object> map = new HashMap<>();

        boolean haveParent;
        // 必须有上级(不是平台邀请的)
        if (Constants.ZERO.equals(fullParent)&&!"13705244452".equals(currentUser.getPhonenumber())) {
            haveParent = false;
        } else {
            haveParent = true;
        }
        map.put("haveParent", haveParent);
        return AjaxResult.success(map);
    }


    @Login
    @ApiOperation("绑定邀请码")
    @PostMapping("/bindInviteCode")
    @RepeatSubmit
    public AjaxResult bindInviteCode(@ApiParam("邀请码") @RequestParam String inviteCode) {

        // 查询当前登录用户
        HcxAppUser currentUser = hcxAppUserService.getOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getId, SecurityUtils.getUserId()));

        String fullParent = currentUser.getInviteFullCode();
        AssertUtils.isTrue(Constants.ZERO.equals(fullParent), "已存在父级无需绑定！");
        HcxAppUser one = hcxAppUserService.getOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getInviteCode, inviteCode));
        AssertUtils.isTrue(ObjectUtil.isNotEmpty(one), "邀请码无效!");
        currentUser.setInviteFullCode(one.getInviteFullCode()+one.getInviteCode());
        return toAjax(hcxAppUserService.updateById(currentUser));

    }


    /**
     * @description: 生成令牌方便测试的时候使用
     * @author: kubilewang
    **/
    @ApiOperation("生成令牌")
    @GetMapping("/createToken")
    public AjaxResult<String> createToken(@ApiParam("用户id") @RequestParam Long userId) {

        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + 5253120 * 1000);

        String compact = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, "f4e2e52034348f86b67cde581c0f9eb5")
                .compact();

        return AjaxResult.success("生成令牌成功","Bearer "+compact);
    }
}
